package com.zhuojy.equity.mall.admin.common.utils;

import com.zhuojy.equity.mall.admin.common.pojo.TreeVO;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 菜单树结构工具类
 */
@Component
public class TreeUtil {
    /**
     * 创建树结构
     * @param regionTrees
     * @return
     */
    public List<TreeVO> tree(List<TreeVO> regionTrees,String id) {
        //返回的节点树
        List<TreeVO> rootNodes = new ArrayList<>();
        Iterator<TreeVO> it = regionTrees.iterator();
        while (it.hasNext()) {
            TreeVO next = it.next();
            //parent（上级Id）为0的是根节点
            if (id.equals(next.getPid())) {
                rootNodes.add(next);
                it.remove();
            }
        }
        //遍历，找到二级节点
        for (TreeVO regionTree : rootNodes) {
            List<TreeVO> child = getChild(regionTrees, regionTree.getId().toString());
            regionTree.setChildren(child);
        }
        return rootNodes;

    }

    /**
     * 查子节点
     *
     * @param regions
     * @param pid
     * @return
     */
    private List<TreeVO> getChild(List<TreeVO> regions, String pid) {

        //子节点列表
        List<TreeVO> childList = new ArrayList<>();
        Iterator<TreeVO> it = regions.iterator();
        while (it.hasNext()) {
            TreeVO regionTree = it.next();
            if (pid.equals(regionTree.getPid())) {
                childList.add(regionTree);
                it.remove();
            }
        }

        //遍历 递归获取子节点的子节点
        for (TreeVO regionTree : childList) {
            List<TreeVO> child = getChild(regions, regionTree.getId().toString());
            regionTree.setChildren(child);
        }
        //递归出口  childList长度为0
        if (childList.size() == 0) {
            return new ArrayList<>();
        }
        return childList;
    }
}
